package com.flx.noodle.websocket.security;


import com.flx.noodle.websocket.entity.SSOUser;

import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import util.HttpUtils;
import util.WsConstant;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.net.URLDecoder;


/**
 * Created by fenglixiong on 2017/10/3.
 */
@Component
public class SignInterceptor extends HandlerInterceptorAdapter implements InitializingBean {

    protected final Log logger = LogFactory.getLog(getClass());

    @Value("${websocket.need_check_url}")
    private String[] need_check_url;
    @Value("${websocket.not_check_url}")
    private String[] not_check_url;

    @Value("${websocket.remote_check_url}")
    private String remote_check_url;


    @Override
    @SuppressWarnings("all")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        String ctx = request.getContextPath();//比如/admin
        boolean check_need = false;
        for(String s:this.not_check_url){
            if(url.startsWith(ctx + s)){
                return true;
            }
        }
        for(String s:this.need_check_url){
            if(url.startsWith(ctx + s)){
                check_need = true;
                break;
            }
        }
        if(check_need) {
            SSOUser ssoUser = (SSOUser) request.getSession().getAttribute(WsConstant.WEBSOCKET_SESSION_KEY);
            if (ssoUser == null) {
                logger.info("用户未登陆！！！请求失败！！！");
                return false;
            } else {
                logger.info("经过检查本请求的用户为：" + ssoUser.getUserId());
            }
        }else {
            logger.info("无需检查，成功通过拦截器！");
        }
        return true;
    }


    public String getSessionIdFromCookie(String session_cookie) {
        if (session_cookie != null) {
            try {
                String value = URLDecoder.decode(session_cookie, "UTF-8");
                logger.info("decoded:" + value);
                String[] ss = value.split("@");
                if (ss.length == 3) {
                    String sessionId_cookie = ss[0];
                    logger.info(sessionId_cookie + "\t");
                    return sessionId_cookie;
                } else {
                    logger.info("cookie中数据长度不正确");
                }
            } catch (Exception e) {
                logger.info("check session error:" + e.getMessage());
                e.printStackTrace();
            }
        }
        return null;
    }

    public SSOUser remoteCheckSessionBySessionId(String sessionId)throws Exception{
        String url = this.remote_check_url+"/user/getUserBySessionId.json?sessionId="+sessionId;
        String res = HttpUtils.doRemoteGet(url,null);
        if(res!=null){
            return new Gson().fromJson(res,SSOUser.class);
        }
        return null;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    public void afterPropertiesSet() throws Exception {
    }
}
